//
//  ImageHelper.swift
//  AppHelper
//
//  Created by Apple on 2018/1/26.
//  Copyright © 2018年 Apple. All rights reserved.
//

import Cocoa

extension NSImage {
    
    /// 裁剪图片
    ///
    /// - Parameter toSize: 需要裁剪的大小
    /// - Returns: 裁剪后的图片
    func tailor(toSize: NSSize) -> NSImage? {
        
        let pointOrigin = NSPoint(x: (size.width - toSize.width) * 0.5,
                                y: (size.height - toSize.height) * 0.5)
        
        return NSImage(size: toSize, flipped: false, drawingHandler: { rect -> Bool in
            self.draw(in: rect, from: NSRect(origin: pointOrigin, size: rect.size), operation: .copy, fraction: 1.0)
            return true
        })
    }

    func writePNG(to path: String) -> Bool {
        guard let tiffData = tiffRepresentation else { return false }
        let imgRep = NSBitmapImageRep(data: tiffData)
        guard let data = imgRep?.representation(using: .png, properties: [:]) else { return false }
        do {
            try data.write(to: URL(fileURLWithPath: path))
            return true
        } catch _ {
            return false
        }
    }
}

